""" category仓储操作 """

# from sqlalchemy import func
from sqlalchemy.orm import Session
from model.category import Category
from schema.category import CategoryUpdate


def get_categories(db: Session):
    """ 获取分类列表 """
    return db.query(Category).all()


def get_cate_arts(db: Session, cate_id: int):
    """ 获取分类下文章列表 """
    return db.query(Category).filter(Category.id == cate_id).first().articles


def update_category(db: Session, cate_id: int, update_category: CategoryUpdate):
    """ 更新分类信息 """
    category = db.query(Category).filter(
        Category.id == cate_id).first()

    if category:
        update_dict = update_category.dict(exclude_unset=True)
        for k, v in update_dict.items():
            setattr(category, k, v)
        db.commit()
        db.flush()
        db.refresh(category)
        return category


def delete_category(db: Session, cate_id: int):
    """ 删除分类 """
    category = db.query(Category).filter(
        Category.id == cate_id).first()
    if category:
        db.delete(category)
        db.commit()
        db.flush()
        return category


def get_by_name(db: Session, name):
    """ 通过名称获取分类 """
    return db.query(Category).filter(Category.name == name).first()


def create_category(db, name):
    """ 创建分类 """
    new_cate = Category(name=name)
    db.add(new_cate)
    db.commit()
    db.refresh(new_cate)
    return new_cate


def get_by_id(db, cate_id):
    """ 通过id获取分类 """
    return db.query(Category).filter(Category.id == cate_id).first()
